package com.hsyt.pms.controller.system;

import com.alibaba.dubbo.config.annotation.Reference;
import com.hsyt.pfc.support.rpc.PageResult;
import com.hsyt.pfc.support.util.EnumToDataUtil;
import com.hsyt.pfc.support.util.LoggerUtil;
import com.hsyt.pms.api.common.PltLog;
import com.hsyt.pms.api.common.ResultMessage;
import com.hsyt.pms.api.dto.system.SysUserDto;
import com.hsyt.pms.api.enums.Able;
import com.hsyt.pms.api.enums.Status;
import com.hsyt.pms.api.vo.system.SysUserVo;
import com.hsyt.pms.controller.base.BaseController;
import com.hsyt.pms.sys.dubbo.SysUserService;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import java.text.MessageFormat;
import java.util.Date;
import java.util.List;

/**
 * @ClassName: SysUserController
 * @Description: 用户管理服务控制层
 * @author: wangze@hsyuntai.com
 * @date: 2019/1/29 18:19
 */
@RestController
@RequestMapping("/pms/system/user")
public class SysUserController extends BaseController {

    private static final Logger LOGGER = LoggerFactory.getLogger(SysUserController.class);

    @Reference(group = "pmsSystem", registry = "pms", version = "0.0.1")
    private SysUserService sysUserService;

    @RequestMapping(value = "/editUserWin")
    public ModelAndView editUserWin(ModelMap model, @RequestParam("type") String type, @RequestParam("id") Long id) {
        model.put("type", type);
        model.put("id", id);
        return new ModelAndView("system/win/editUser", model);
    }

    @PltLog(log = "新增或者编辑一个用户")
    @RequestMapping(value = "/saveUser")
    public @ResponseBody
    ResultMessage saveEditUser(@RequestBody SysUserDto dto, HttpServletRequest request) {
        ResultMessage result = new ResultMessage(true, "成功");
        try {
            sysUserService.saveAdmin(dto);
        } catch (Exception e) {
            LoggerUtil.error(LOGGER, "save error: {0}", e.getMessage());
            result.change(false, "保存失败,错误信息:" + e.getMessage());
        }
        return result;
    }

    @PltLog(log = "编辑一个用户")
    @RequestMapping(value = "/editUser")
    public @ResponseBody
    ResultMessage editUser(@RequestBody SysUserDto admin, HttpServletRequest request) {
        ResultMessage result = new ResultMessage(true, "操作成功");
        try {
            sysUserService.updateUserByKeySelective(admin);
        } catch (Exception e) {
            LoggerUtil.error(LOGGER, "edit error: {0}", e.getMessage());
            result.change(false, "操作失败" + e.getMessage());
        }
        return result;
    }

    @PltLog(log = "查询一个用户的信息")
    @RequestMapping(value = "/oneAdminInfo/{id}")
    public @ResponseBody
    ResultMessage oneAdminInfo(@PathVariable("id") Long id) {
        ResultMessage result = new ResultMessage(true, "操作成功");
        try {
            result.setContent(sysUserService.selectUserByKey(id));
        } catch (Exception e) {
            LoggerUtil.error(LOGGER, "findOneAdminInfo error: {0}", e.getMessage());
            result.change(false, "获取失败:" + e.getMessage());
        }
        return result;
    }

    @PltLog(log = "初始化用户页面")
    @RequestMapping(value = "/page")
    public ModelAndView openPage(ModelMap model) {
        String statusComboData = EnumToDataUtil.getDHEnumsValuesFromEnum(Status.class);
        String ableComboData = EnumToDataUtil.getDHEnumsValuesFromEnum(Able.class);
        model.addAttribute("statusComboData", statusComboData);
        model.addAttribute("ableComboData", ableComboData);
        return new ModelAndView("system/pageUser", model);
    }

    @PltLog(log = "分页查询用户")
    @RequestMapping(value = "/findPageData")
    public @ResponseBody
    PageResult findPageData(@RequestBody SysUserDto admin) {
        PageResult<SysUserVo> pageResult = new PageResult<SysUserVo>();
        try {
            pageResult = sysUserService.searchPageDataByDto(admin);
        } catch (Exception e) {
            pageResult.setResult(false);
            String message = MessageFormat.format("SysUserController.searchPageData error: {0}", e.getMessage());
            pageResult.setMessage(message);
            LoggerUtil.error(LOGGER, message);
        }
        return pageResult;
    }

    @PltLog(log = "删除一个用户")
    @RequestMapping(value = "/delUser")
    public @ResponseBody
    ResultMessage delUser(@RequestParam("id") Long id, HttpServletRequest request) {
        ResultMessage result = new ResultMessage(true, "删除成功");
        SysUserDto SysUserDto = new SysUserDto();
        try {
            SysUserDto.setId(id);
            SysUserDto.setEnabled(Able.DISABLED.getCode());
            sysUserService.updateUserByKeySelective(SysUserDto);
        } catch (Exception e) {
            result.change(false, "删除失败" + e.getMessage());
            LoggerUtil.error(LOGGER, "delUser error: {0}", e.getMessage());
        }
        return result;
    }

    @RequestMapping(value = "/gotoAuthorityWin")
    public ModelAndView gotoAuthorityWin(ModelMap model, @RequestParam("id") String id) {
        if (id == null) {
            return new ModelAndView("system/alipay/authAlipayUser", model);
        }
        return new ModelAndView("system/win/authorityUser", model);
    }

    @PltLog(log = "启用/停用用户")
    @RequestMapping(value = "/doUndo")
    public @ResponseBody
    ResultMessage doUndo(@RequestBody SysUserDto dto, HttpServletRequest request) {
        ResultMessage result = new ResultMessage(true, "操作成功");
        try {
            dto.setGmtModify(new Date());
            sysUserService.updateUserByKeySelective(dto);
        } catch (Exception e) {
            result.change(false, "操作失败" + e.getMessage());
            LoggerUtil.error(LOGGER, "SysUserController-doUndo error:{0} param:{1}", e.getMessage(), dto);
        }
        return result;
    }

    @RequestMapping(value = "/toEditForm")
    public ModelAndView toEditForm(ModelMap model, @RequestParam("formType") String formType) {
        model.put("formType", formType);
        return new ModelAndView("system/formUser");
    }

    @PltLog(log = "保存用户")
    @RequestMapping(value = "/save")
    public @ResponseBody
    ResultMessage save(@RequestBody SysUserDto dto, String formType, HttpServletRequest request) {
        ResultMessage result = new ResultMessage(true, "成功");
        try {
            if (dto.getId() == null) {
                sysUserService.saveAdmin(dto);
            } else {
                sysUserService.updateUserByKeySelective(dto);
            }
        } catch (Exception e) {
            result.change(false, "保存失败 , 错误信息:" + e.getMessage());
            LoggerUtil.error(LOGGER, "SysParamController-save error: {0}", e.getMessage());
        }
        return result;
    }

    @RequestMapping(value = "/toRoleSetting")
    public ModelAndView toRoleSetting(ModelMap model, @RequestParam("userId") Long userId, @RequestParam("orgId") Long orgId)
            throws Exception {
        try {
            List<Long> roleIds = null;
            model.put("userId", userId);
            model.put("orgId", orgId);
            if (userId != null) {
                roleIds = sysUserService.queryUserRole(userId);
            }
            model.put("roleIds", StringUtils.join(roleIds, ","));
        } catch (Exception e) {
            LoggerUtil.error(LOGGER, "SysParamController-save error: {0}", e.getMessage());
        }

        return new ModelAndView("system/pageUserRole");
    }

    @RequestMapping(value = "/saveUserRoles")
    public @ResponseBody
    ResultMessage saveUserRoles(ModelMap model, @RequestParam("userId") Long userId,
                                @RequestParam("roleIds") List<Long> roleIds) {

        ResultMessage result = new ResultMessage(true, "成功");
        try {
            sysUserService.saveUserRole(userId, roleIds);
        } catch (Exception e) {
            result.change(false, "保存失败 , 错误信息:" + e.getMessage());
            LoggerUtil.error(LOGGER, "SysParamController-save error: {0}", e.getMessage());
        }
        return result;
    }
}
